import {
  getFileList,
  getFile,
} from "@/api/login/login";
import {
  Message
} from "ant-design-vue";


//todo 请求文件列表
/* 
  data: {
    type: string;
    appId: string;
  }
*/
const searchFilesList = async (data, pageSize = 1) => {
  const requestData = {
    pageIndex: 0,
    pageSize: pageSize,
    type: [data.type],
    sort: '"uploadTime" DESC',
    condition: data.appId,
  }
  return await getFileList(requestData);
}

const conversionBase64 = (blob) => {
  const reader = new FileReader();
  reader.readAsDataURL(blob);
  return new Promise(resolve => {
    reader.onload = ({target: {result}}) => {
      resolve(result)
    }
  })
}

const saveFileToLocal = (blob, fileName) => {
  const a = document.createElement("a");
  const url = window.URL.createObjectURL(blob);
  const filename = fileName;
  a.href = url;
  a.download = filename;
  a.click();
  window.URL.revokeObjectURL(url);
  a.remove();
}

//todo 下载文件
/* 
  data: {
    id: string
    fileName: string
    originName: string
  }

  type: string // pic | file ;   //type === pic 返回base64 否则直接下载打开
*/
const downFile = async (data, type) => {
  const {
    success,
    data: blob
  } = await getFile({
    id: data.id,
    fileName: data.saveName,
  })
  if (success) {
    if (type === 'pic') {
      return await conversionBase64(blob);
    } else {
      saveFileToLocal(blob, data.originName);
    }
  } else {
    Message.warning("请求下载文件失败");
  }

}

export {
  searchFilesList,
  downFile
}